import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_250303/datas/home_banner_data.dart';
import 'package:flutter_250303/pages/home/home_vm.dart';
import 'package:flutter_250303/pages/web_view_page.dart';
import 'package:flutter_250303/route/route_utils.dart';
import 'package:flutter_250303/route/routes.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../datas/home_list_data.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  HomeViewModel viewModel = HomeViewModel();
  RefreshController refreshController = RefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // viewModel.initDio();
    viewModel.getBanner();
    viewModel.getHomeList(false);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<HomeViewModel>(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        body: SafeArea(
            child: SmartRefresher(
          controller: refreshController,
          enablePullUp: true,
          enablePullDown: true,
          header: ClassicHeader(),
          footer: ClassicFooter(),
          onRefresh: () {
            // 下拉刷新
            viewModel.getBanner().then((value) {
              viewModel.getHomeList(false).then((value) {
                refreshController.refreshCompleted();
              });
            });
          },
          onLoading: () {
            // 上拉
            print("===sf===> up");
            viewModel.getHomeList(true).then((value) {
              refreshController.loadComplete();
            });
          },
          child: SingleChildScrollView(
              // banner和listview一起滑动
              child: Column(children: [
            _banner(),
            _listView(),
          ])),
        )),
      ),
    );
  }

  Widget _banner() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return SizedBox(
        height: 150.h,
        width: double.infinity,
        child: Swiper(
          indicatorLayout: PageIndicatorLayout.NONE,
          autoplay: true,
          pagination: const SwiperPagination(),
          control: const SwiperControl(),
          itemCount: vm.bannerList?.length ?? 0,
          itemBuilder: (context, index) {
            return Container(
              // margin: EdgeInsets.all(15.r),
              height: 150.h,
              color: Colors.grey,
              child: Image.network(
                vm.bannerList?[index]?.imagePath ?? "",
                fit: BoxFit.fill,
              ),
            );
          },
        ),
      );
    });
  }

  Widget _listView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return ListView.builder(
        shrinkWrap: true, // SingleChildScrollView 获取滑动的总高度（所有的item）
        physics: NeverScrollableScrollPhysics(), // 禁止滑动
        itemBuilder: (context, index) {
          return _listItemView(viewModel.listData?[index]);
        },
        itemCount: viewModel.listData?.length ?? 0,
      );
    });
  }

  Widget _listItemView(HomeListItemData? item) {
    String name = (item?.author ?? "").isNotEmpty
        ? item?.author ?? ""
        : item?.shareUser ?? "";
    // InkWell 点击水波纹效果
    return GestureDetector(
        onTap: () {
          // Navigator.push(context, MaterialPageRoute(builder: (context) {
          //   return WebViewPage(title: "首页而来 ",);
          // }));
          // Navigator.pushNamed(context, RoutePath.webViewPage);
          RouteUtils.pushForNamed(context, RoutePath.webViewPage,
              arguments: {"name": "home_page name web"});
        },
        child: Container(
            margin: EdgeInsets.only(
                top: 15.r, bottom: 15.r, left: 10.r, right: 10.r),
            padding:
                EdgeInsets.only(top: 5.r, bottom: 5.r, left: 10.r, right: 10.r),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.black12, width: 0.5.r),
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(23.r),
                      child: Image.network(
                        "https://img1.baidu.com/it/u=702662228,231598915&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500",
                        width: 46.r,
                        height: 46.r,
                        fit: BoxFit.fill,
                      ),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    Text(
                      name,
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 20.sp,
                      ),
                    ),
                    Expanded(child: SizedBox()),
                    Text(
                      item?.niceShareDate ?? "",
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 20.sp,
                      ),
                    ),
                    SizedBox(
                      width: 5,
                    ),
                    item?.type?.toInt() == 1
                        ? Text(
                            "置顶",
                            style: TextStyle(
                                color: Colors.blue,
                                fontSize: 20.sp,
                                fontWeight: FontWeight.bold),
                          )
                        : SizedBox(),
                  ],
                ),
                SizedBox(
                  height: 5.h,
                ),
                Text(
                  item?.title ?? "",
                  style: TextStyle(color: Colors.black, fontSize: 15.sp),
                ),
                SizedBox(
                  height: 5.h,
                ),
                Row(
                  children: [
                    Text(
                      item?.chapterName ?? "",
                      style: TextStyle(color: Colors.blue, fontSize: 20),
                    ),
                    Expanded(child: SizedBox()),
                    Container(
                      color: Colors.red,
                      width: 30.r,
                      height: 30.r,
                    )
                  ],
                )
              ],
            )));
  }
}
